// API基础URL
const API_BASE_URL = '/api';

// DOM元素（将在DOMContentLoaded中初始化）
let loginSection, mainContent, loginForm, logoutBtn;
let instructionTableBody, instructionHistoryTableBody;
let addInstructionModal, addInstructionForm, closeAddInstructionModal;
let instructionTypeFilter, startDateFilter, endDateFilter, filterInstructionsBtn;
let refreshCurrentBtn, refreshHistoryBtn, addInstructionBtn;

// JWT令牌
let authToken = localStorage.getItem('authToken');

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成，开始初始化...');
    
    // 初始化DOM元素
    initializeDOMElements();
    
    // 检查用户是否已登录
    if (authToken) {
        showMainContent();
        loadAllData();
    } else {
        showLoginSection();
    }
    
    // 绑定事件监听器
    bindEventListeners();
});

// 初始化DOM元素
function initializeDOMElements() {
    // 认证相关元素
    loginSection = document.getElementById('loginSection');
    mainContent = document.getElementById('mainContent');
    loginForm = document.getElementById('loginForm');
    logoutBtn = document.getElementById('logoutBtn');

    // 表格元素
    instructionTableBody = document.querySelector('#instructionTable tbody');
    instructionHistoryTableBody = document.querySelector('#instructionHistoryTable tbody');

    // 模态框元素
    addInstructionModal = document.getElementById('addInstructionModal');
    addInstructionForm = document.getElementById('addInstructionForm');
    closeAddInstructionModal = document.querySelector('#addInstructionModal .close');

    // 筛选元素
    instructionTypeFilter = document.getElementById('instructionTypeFilter');
    startDateFilter = document.getElementById('startDateFilter');
    endDateFilter = document.getElementById('endDateFilter');
    filterInstructionsBtn = document.getElementById('filterInstructionsBtn');
    
    // 按钮元素
    refreshCurrentBtn = document.getElementById('refreshCurrentBtn');
    refreshHistoryBtn = document.getElementById('refreshHistoryBtn');
    addInstructionBtn = document.getElementById('addInstructionBtn');
}

// 绑定事件监听器
function bindEventListeners() {
    console.log('开始绑定事件监听器...');
    
    // 登录表单提交
    if (loginForm) {
        loginForm.addEventListener('submit', handleLogin);
        console.log('已绑定登录表单提交事件');
    }
    
    // 登出按钮
    if (logoutBtn) {
        logoutBtn.addEventListener('click', handleLogout);
        console.log('已绑定登出按钮点击事件');
    }
    
    // 创建指令表单提交
    if (addInstructionForm) {
        addInstructionForm.addEventListener('submit', handleAddInstructionSubmit);
        console.log('已绑定创建指令表单提交事件');
    }
    
    // 关闭模态框
    if (closeAddInstructionModal) {
        closeAddInstructionModal.addEventListener('click', closeAddInstructionModalFunc);
        console.log('已绑定关闭模态框事件');
    }
    
    // 点击模态框外部关闭
    if (addInstructionModal) {
        addInstructionModal.addEventListener('click', function(event) {
            if (event.target === addInstructionModal) {
                closeAddInstructionModalFunc();
            }
        });
        console.log('已绑定点击模态框外部关闭事件');
    }
    
    // 筛选按钮
    if (filterInstructionsBtn) {
        filterInstructionsBtn.addEventListener('click', handleFilterInstructions);
        console.log('已绑定筛选按钮点击事件');
    }
    
    // 刷新按钮
    if (refreshCurrentBtn) {
        refreshCurrentBtn.addEventListener('click', loadCurrentInstructions);
        console.log('已绑定刷新当前指令按钮点击事件');
    }
    
    if (refreshHistoryBtn) {
        refreshHistoryBtn.addEventListener('click', loadHistoryInstructions);
        console.log('已绑定刷新历史指令按钮点击事件');
    }
    
    // 创建指令按钮
    if (addInstructionBtn) {
        addInstructionBtn.addEventListener('click', openAddInstructionModal);
        console.log('已绑定创建指令按钮点击事件');
    }
    
    // 模块导航
    setupModuleNavigation();
    
    console.log('事件监听器绑定完成');
}

// 设置模块导航
function setupModuleNavigation() {
    const navLinks = document.querySelectorAll('.module-nav a');
    const sections = document.querySelectorAll('.module-section');
    
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            // 移除所有活动状态
            navLinks.forEach(l => l.classList.remove('active'));
            sections.forEach(s => s.classList.remove('active'));
            
            // 添加当前活动状态
            this.classList.add('active');
            const targetSection = document.querySelector(this.getAttribute('href'));
            if (targetSection) {
                targetSection.classList.add('active');
            }
        });
    });
}

// 显示登录界面
function showLoginSection() {
    console.log('显示登录界面');
    if (loginSection) loginSection.style.display = 'block';
    if (mainContent) mainContent.style.display = 'none';
}

// 显示主内容界面
function showMainContent() {
    console.log('显示主内容界面');
    if (loginSection) loginSection.style.display = 'none';
    if (mainContent) mainContent.style.display = 'block';
}

// 处理登录
function handleLogin(event) {
    event.preventDefault();
    
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    
    fetch(`${API_BASE_URL}/auth/login`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            authToken = data.data.token;
            localStorage.setItem('authToken', authToken);
            showMainContent();
            loadAllData();
        } else {
            alert('登录失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('登录失败:', error);
        alert('登录失败');
    });
}

// 处理登出
function handleLogout() {
    authToken = null;
    localStorage.removeItem('authToken');
    showLoginSection();
}

// 关闭创建指令模态框
function closeAddInstructionModalFunc() {
    console.log('关闭创建指令模态框');
    if (addInstructionModal) {
        addInstructionModal.style.display = 'none';
    }
    
    // 重置表单
    if (addInstructionForm) addInstructionForm.reset();
}

// 打开创建指令模态框
function openAddInstructionModal() {
    console.log('打开创建指令模态框');
    if (addInstructionModal) {
        if (addInstructionForm) addInstructionForm.reset();
        addInstructionModal.style.display = 'block';
    }
}

// 处理创建指令表单提交
function handleAddInstructionSubmit(event) {
    event.preventDefault();
    
    const instructionData = {
        taskId: document.getElementById('taskId').value,
        taskType: document.getElementById('taskType').value,
        palletId: document.getElementById('palletId').value,
        startLocation: document.getElementById('startLocation').value,
        targetLocation: document.getElementById('targetLocation').value,
        startDevice: document.getElementById('startDevice').value,
        endDevice: document.getElementById('endDevice').value,
        materialCode: document.getElementById('materialCode').value,
        materialName: document.getElementById('materialName').value,
        executeQuantity: parseInt(document.getElementById('executeQuantity').value) || 0
    };
    
    createInstruction(instructionData);
}

// 处理筛选指令历史
function handleFilterInstructions() {
    const type = instructionTypeFilter ? instructionTypeFilter.value : '';
    const startDate = startDateFilter ? startDateFilter.value : '';
    const endDate = endDateFilter ? endDateFilter.value : '';
    filterInstructions(type, startDate, endDate);
}

// 加载所有数据
function loadAllData() {
    loadCurrentInstructions();
    loadHistoryInstructions();
}

// 加载当前指令
function loadCurrentInstructions() {
    if (!authToken) return;
    
    fetch(`${API_BASE_URL}/instructions/current`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderInstructionTable(data.data);
            }
        })
        .catch(error => {
            console.error('加载当前指令数据失败:', error);
        });
}

// 渲染当前指令表格
function renderInstructionTable(instructions) {
    if (!instructionTableBody) return;
    
    instructionTableBody.innerHTML = '';
    
    instructions.forEach(instruction => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${instruction.id}</td>
            <td>${instruction.task_id}</td>
            <td>${instruction.task_type}</td>
            <td>${instruction.pallet_id || '-'}</td>
            <td>${instruction.start_location || '-'}</td>
            <td>${instruction.target_location || '-'}</td>
            <td>${instruction.start_device || '-'}</td>
            <td>${instruction.end_device || '-'}</td>
            <td>${instruction.material_code || '-'}</td>
            <td>${instruction.material_name || '-'}</td>
            <td>${instruction.execute_quantity || 0}</td>
            <td>${getInstructionStatusText(instruction.status)}</td>
            <td>${instruction.completion_method || '-'}</td>
            <td>${instruction.completion_time ? formatDate(instruction.completion_time) : '-'}</td>
            <td>
                <button class="btn-primary" onclick="viewInstruction(${instruction.id})">查看</button>
                <button class="btn-primary" onclick="forcePostInstruction(${instruction.id})">强制过账</button>
                <button class="btn-primary" onclick="cancelInstruction(${instruction.id})">撤销</button>
            </td>
        `;
        instructionTableBody.appendChild(row);
    });
}

// 加载历史指令
function loadHistoryInstructions() {
    if (!authToken) return;
    
    fetch(`${API_BASE_URL}/instructions/history`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderInstructionHistoryTable(data.data);
            }
        })
        .catch(error => {
            console.error('加载历史指令数据失败:', error);
        });
}

// 渲染历史指令表格
function renderInstructionHistoryTable(instructions) {
    if (!instructionHistoryTableBody) return;
    
    instructionHistoryTableBody.innerHTML = '';
    
    instructions.forEach(instruction => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${instruction.id}</td>
            <td>${instruction.task_id}</td>
            <td>${instruction.task_type}</td>
            <td>${instruction.pallet_id || '-'}</td>
            <td>${instruction.start_location || '-'}</td>
            <td>${instruction.target_location || '-'}</td>
            <td>${instruction.start_device || '-'}</td>
            <td>${instruction.end_device || '-'}</td>
            <td>${instruction.material_code || '-'}</td>
            <td>${instruction.material_name || '-'}</td>
            <td>${instruction.execute_quantity || 0}</td>
            <td>${getInstructionStatusText(instruction.status)}</td>
            <td>${instruction.completion_method || '-'}</td>
            <td>${instruction.completion_time ? formatDate(instruction.completion_time) : '-'}</td>
        `;
        instructionHistoryTableBody.appendChild(row);
    });
}

// 筛选指令历史
function filterInstructions(type, startDate, endDate) {
    // 这里可以实现指令历史筛选逻辑
    alert('指令历史筛选功能待实现');
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
}

// 获取指令状态文本
function getInstructionStatusText(status) {
    const statusMap = {
        'not_issued': '未下发',
        'issued': '已下发',
        'executing': '正在执行',
        'completed': '已完成',
        'cancelled': '已撤销'
    };
    return statusMap[status] || status;
}

// 创建指令
function createInstruction(instructionData) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    fetch(`${API_BASE_URL}/instructions`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify(instructionData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('指令创建成功');
            closeAddInstructionModalFunc();
            loadAllData();
        } else {
            alert('创建指令失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('创建指令失败:', error);
        alert('创建指令失败');
    });
}

// 查看指令详情
function viewInstruction(id) {
    alert(`查看指令详情功能待实现，指令ID: ${id}`);
    // 这里可以实现查看详情功能
}

// 强制过账指令
function forcePostInstruction(id) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    if (confirm('确定要强制过账这个指令吗？')) {
        fetch(`${API_BASE_URL}/instructions/${id}/force-post`, {
            method: 'PUT',
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('指令强制过账成功');
                loadAllData();
            } else {
                alert('强制过账失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('强制过账指令失败:', error);
            alert('强制过账指令失败');
        });
    }
}

// 撤销指令
function cancelInstruction(id) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    if (confirm('确定要撤销这个指令吗？')) {
        fetch(`${API_BASE_URL}/instructions/${id}/cancel`, {
            method: 'PUT',
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('指令撤销成功');
                loadAllData();
            } else {
                alert('撤销指令失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('撤销指令失败:', error);
            alert('撤销指令失败');
        });
    }
}